package file_safeBox

import (
	"crypto/md5"
	"crypto/sha512"
	"encoding/hex"
	"fmt"
	"gitlab.local/golibrary/utils"
	"path/filepath"
	"strings"
)

const cmd = `echo -e "\n" | mount -t ecryptfs '%s' '%s' -o 'key=passphrase:passphrase_passwd=%s,ecryptfs_cipher=aes,ecryptfs_key_bytes=32,ecryptfs_passthrough=n,ecryptfs_enable_filename_crypto=y,no_sig_cache'`

// mount 挂载保险箱
func (s *SafeBox) mount(path, toPath, key string) error {
	if s.IsMount(toPath) {
		return nil
	}
	if len(key) > 15 {
		//只拿秘钥的前15位做加密
		key = key[:15]
	}
	sum := md5.Sum([]byte(key))
	_, err := utils.ShellExec(fmt.Sprintf(cmd, path, toPath, hex.EncodeToString(sum[:])))
	return err
}

// toPath 卸载保险箱
func (s *SafeBox) umount(toPath string) error {
	if s.IsMount(toPath) {
		_, err := utils.ShellExec(fmt.Sprintf(`umount -v '%s'`, toPath))
		return err
	}
	return nil
}

// IsMount 是否挂载
func (s *SafeBox) IsMount(toPath string) bool {
	if toPath == "" {
		return false
	}
	toPath, err := filepath.Abs(toPath)
	if err != nil {
		return false
	}
	cmd := fmt.Sprintf(`/usr/sbin/df-json | grep -E '%s$' | grep " ecryptfs "`, toPath)
	res, err := utils.ShellExec(cmd)
	if err != nil {
		return false
	}
	return strings.TrimSpace(res) != ""
}

// enKey 加密key
func (s *SafeBox) enKey(key string) (string, error) {
	sum512 := sha512.Sum512([]byte(key))
	by := make([]byte, len(sum512))
	copy(by, sum512[:])
	ss := md5.Sum(by)
	return hex.EncodeToString(ss[:]), nil
}
